package com.theme.passport.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.theme.common.mvc.utils.PageUtils;
import com.theme.common.mvc.utils.Query;
import com.theme.passport.dao.theme.TabActivationCodeDao;
import com.theme.passport.entity.theme.TabActivationCode;
import com.theme.passport.service.TabActivationCodeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.Random;

@Service("TabActivationCodeService")
public class TabActivationCodeServiceImpl extends ServiceImpl<TabActivationCodeDao, TabActivationCode> implements TabActivationCodeService {


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String isUsed = (String) params.get("isUsed");
        String activationCode = (String) params.get("activationCode");
        IPage<TabActivationCode> page = this.page(
                new Query<TabActivationCode>().getPage(params),
                new LambdaQueryWrapper<TabActivationCode>()
                        .eq(StringUtils.isNotBlank(activationCode),TabActivationCode::getActivationCode,activationCode)
                        .eq(StringUtils.isNotBlank(isUsed), TabActivationCode::getIsUsed, isUsed)
                        .orderByDesc(TabActivationCode::getCreateTime)
        );
        return new PageUtils(page);
    }

    @Override
    public String gen() {
        int codeLength = 12;
        String code = generateCode(codeLength);
        TabActivationCode codeEntity = new TabActivationCode();
        codeEntity.setActivationCode(code);
        codeEntity.setIsUsed("0");
        codeEntity.setCreateTime(new Date());
        this.save(codeEntity);
        return  code;

    }

    @Override
    public void zf(Integer id) {
        TabActivationCode codeEntity = this.getById(id);
        codeEntity.setIsUsed("2");
        this.updateById(codeEntity);
    }

    @Resource(name = "redisTemplate")
    private ValueOperations<String, String> redisCache;


    private  final String CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private  String generateCode(int length) {
        StringBuilder code = new StringBuilder(length);
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(CHARACTERS.length());
            code.append(CHARACTERS.charAt(randomIndex));
        }
        return code.toString();
    }

}
